#include "stdafx.h"
#include "cconfigurer.h"
//#include "Plugins/initReader/SimpleIni.h"
//#include "dirHelper/cDirHelper.h"

#include "Plugins\initReader_c89\iniparser.h"

namespace libcvos_vfr
{

	cConfigurer::cConfigurer():
		m_bInit(false),
		m_bFileChange(false)
	{

	}

	cConfigurer::~cConfigurer()
	{
		if (m_bInit 
			&& m_iniParser != NULL 
			&& m_bFileChange)
		{
			FILE* ini_file = fopen(m_strIniFile.c_str(), "w+");
			if (ini_file)
			{
				iniparser_dump_ini((dictionary*)m_iniParser, ini_file);
				fclose(ini_file);
			}
		}
		if (m_iniParser)
		{
			dictionary* pHandle = (dictionary*)m_iniParser;
			iniparser_freedict(pHandle);
			m_iniParser = NULL;
		}

		m_bInit = false;
	}

	bool cConfigurer::loadIniFile(const char *fileName)
	{
		dictionary *dictionary = NULL;
		//FILE *ini_file;
		int ret = 0;

		if (!fileName) 
		{
			fprintf(stderr, "Invalid argurment\n");
			return false;
		}
		dictionary = iniparser_load(fileName);

		if (!dictionary) 
		{
			fprintf(stderr, "cannot parse file: %s\n", fileName);
			return false;
		}
		m_iniParser = dictionary;
		m_strIniFile = fileName;

		m_bInit = true;
		return true;
	}

	void cConfigurer::createIniFile(const char *fileName)
	{
		FILE *ini = NULL;
		if ((ini = fopen(fileName, "w")) == NULL) 
		{
			fprintf(stderr, "iniparser: cannot create example.ini\n");
			return;
		}

		fclose(ini);
	}

	std::string cConfigurer::get_section_value(const char *sectionName, const char *keyName)
	{
		if(!m_bInit)
		{
			fprintf(stderr, "please load ini file first.\n");
			return std::string("");
		}

		char chKeyPairs[512] = {0};
		sprintf(chKeyPairs, "%s:%s", sectionName, keyName);

		const char* pValue = iniparser_getstring((dictionary*)m_iniParser, chKeyPairs, NULL);
		if (pValue != NULL)
			return std::string(pValue);

		return std::string("");
	}

	bool cConfigurer::set_section_value(const char *sectionName, const char *keyName, std::string value)
	{
		if(!m_bInit || NULL == m_iniParser)
		{
			fprintf(stderr, "please load ini file first.\n");
			return false;
		}
		/* set section */
		int ret = iniparser_set((dictionary* )m_iniParser, sectionName, NULL);

		if (ret < 0)
		{
			fprintf(stderr, "cannot set section in: %s\n", m_strIniFile.c_str());
			ret = -1;
			return false;
		}

		char chKeyPairs[512] = { 0 };
		sprintf(chKeyPairs, "%s:%s", sectionName, keyName);
		ret = iniparser_set((dictionary*)m_iniParser, chKeyPairs, value.empty() ?  " " : value.c_str());

		if (ret < 0)
		{
			return false;
		}
		m_bFileChange = true;
		return true;
	}
}
